<template>
  <div class="des-box circle-tab" style="padding:0;">
    <el-form ref="form" :model="entity" label-width="150px" :rules="rules" class="pad-t-1" style="background: white;padding-bottom:1px;">
      <el-form-item label="基本信息" class="one-label">
        <el-row>
          <el-col :span="18">
            <el-form-item label="团长信息">
              <el-row class="flex" :gutter="20">
                <el-col :span="12">
                  <div class="flex v-align-c cursor-p" style="background-color:white;">
                    <label><img :src="entity.avatar" class="user-avatar" v-if="entity.avatar"></label>
                    <div class="font-14 pad-l-10">
                      <div>昵称：{{ entity.nickname}}</div>
                      <div>姓名：{{ entity.realName}}</div>
                      <div>手机：{{ entity.phone}}</div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="团长编号">
              <el-row class="flex" :gutter="20">
                <el-col :span="12">
                  <el-input v-model="entity.commanderCode"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="提货位置">
              <el-row class="flex" :gutter="20">
                <el-col :span="6"><el-input v-model="entity.lng"></el-input></el-col>
                <el-col :span="6"><el-input v-model="entity.lat"></el-input></el-col>
                <el-button type="primary" class="mar-l-10" @click="dialogMapVisible=true">选择坐标</el-button>
              </el-row>
              <el-row class="flex mar-t-10" :gutter="20">
                <el-col :span="12">
                  <el-input v-model="entity.takeAddress"></el-input>
                  <span style="font-size: 10px">点击“选择坐标”按钮输入小区地区搜索并选择具体位置确认即可</span>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="小区设置" class="one-label">
        <el-row>
          <el-col :span="18">
            <el-form-item label="管理小区">
              <el-row class="flex" :gutter="20">
                <el-col :span="4">
                  <el-select class="mar-r-3" v-model="provinceCode" filterable placeholder="请选择省份" @change = "changeProvince()">
                    <el-option v-for="item in provinceList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select class="mar-r-3" v-model="cityCode" filterable placeholder="请选择城市" @change = "changeCity()">
                    <el-option v-for="item in useCityList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="4">
                  <el-select v-model="districtCode" filterable placeholder="请选择区县" @change = "changeDistrict()">
                    <el-option v-for="item in useDistrictList" :key="item.areaCode" :label="item.areaName" :value="item.areaCode">
                    </el-option>
                  </el-select>
                </el-col>
                <el-button type="primary" class="mar-l-10" @click="onShowVillage">选择小区</el-button>
              </el-row>
              <el-row class="flex mar-t-10" :gutter="20">
                <el-col :span="12">
                  <span style="font-size: 10px">必须先设置省市区才可以选择添加管理的小区</span>
                  <el-input v-model="villageNames" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" :readonly="true"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div class="bottom-btn pad-b-15" style="text-align: center">
      <el-button class="pad-l-30 pad-r-30" @click="$router.go(-1)">返回列表</el-button>
      <el-button type="primary" class="pad-l-30 pad-r-30" @click="saveData">保存</el-button>
    </div>

    <el-dialog width="700px" :center="true" v-el-drag-dialog title="选择小区" :visible.sync="dialogPickVillageVisible">
      <el-table :data="villageList" v-loading="listLoading" element-loading-text="加载中" style="width: 100%" >
        <el-table-column width="500px" label="小区" prop="villageName" ></el-table-column>
        <el-table-column width="150px" label="操作" align="center">
          <template slot-scope="scope">
            <el-button :type="scope.row.selectFlag == 1 ? 'info' : 'primary'"  @click="onPickVillage(scope.row)">{{scope.row.selectFlag  == 1 ? '已选择' : '选择'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPickVillageVisible = false">取消</el-button>
        <el-button type="primary" @click="onSelectVillage">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog width="700px" v-el-drag-dialog title="请选择地点" :visible.sync="dialogMapVisible">
      <iframe id="mapPage" width="100%" height="600px" frameborder=0
              src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&referer=web">
      </iframe>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMapVisible = false">取消</el-button>
        <el-button type="primary" @click="onSetLocation(loc)">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { getVillageCommander, listByDistrictCode, listByCommanderId, saveCommander } from '@/api/user/commander'
  import { listArea } from '@/api/area/area'
  import elDragDialog from '@/directive/el-dragDialog'

  export default {
    directives: {
      // 拖动窗口
      elDragDialog
    },

    data() {
      return {
        entity: {},
        commanderId: '',
        villageNames: '',
        provinceList: [],
        cityList: [],
        districtList: [],
        useCityList: [],
        useDistrictList: [],
        provinceCode: '',
        cityCode: '',
        districtCode: '',
        selectedDistrictCode: '',
        rules: {},
        dialogPickVillageVisible: false,
        villageList: [],
        villages: [],
        listLoading: false,
        dialogMapVisible: false,
        loc: null
      }
    },
    // 初始化页面
    created() {
      window.addEventListener('message', function(event) {
        // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
        const loc = event.data
        if (loc && loc.module === 'locationPicker') {
          // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
          this.loc = { ... loc }
        }
      }, false)
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.commanderId) {
        this.commanderId = queryParams.commanderId
      }
      this.init()
    },
    methods: {
      init() {
        getVillageCommander(this.commanderId).then(response => {
          if (response.isError) return
          this.entity = response.data
          if (this.entity.village) {
            this.provinceCode = this.entity.village.provinceName
            this.cityCode = this.entity.village.cityName
            this.districtCode = this.entity.village.districtName
            this.villageNames = this.entity.village.villageName
          }
        })
        listArea().then(response => {
          this.provinceList = response.data.provinceList
          this.cityList = response.data.cityList
          this.districtList = response.data.districtList
        })
        listByCommanderId({ commanderId: this.commanderId }).then(response => {
          if (response.isError) return
          this.villageList = response.data
        })
      },
      // 保存用户信息
      saveData() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (!this.entity.lng) {
              this.$message.error('经度不能为空')
              return
            }
            if (!this.entity.lat) {
              this.$message.error('纬度不能为空')
              return
            }
            if (!this.entity.takeAddress) {
              this.$message.error('提货地址不能为空')
              return
            }
            this.villageList.forEach(village => {
              village.commanderId = this.commanderId
            })
            this.entity.villages = this.villages
            saveCommander(this.entity).then((response) => {
              if (response.isError) return
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.$router.go(-1)
            })
          }
        })
      },
      changeProvince() {
        this.changeCity()
        this.cityCode = ''
      },
      changeCity() {
        const provinceList = this.provinceList
        const provinceCode = this.provinceCode
        let provinceId = null
        provinceList.filter(province => {
          if (province.areaCode === provinceCode) {
            provinceId = province.areaId
            return true
          }
        })
        const cityList = this.cityList
        this.useCityList = []
        cityList.forEach(city => {
          const parentId = city.parentId
          if (parentId === provinceId) {
            this.useCityList.push(city)
          }
        })
        this.changeDistrict()
        this.districtCode = ''
      },
      changeDistrict() {
        const cityList = this.useCityList
        const cityCode = this.cityCode
        let cityId = null
        cityList.filter(city => {
          if (city.areaCode === cityCode) {
            cityId = city.areaId
            return true
          }
        })
        const districtList = this.districtList
        this.useDistrictList = []
        districtList.forEach(district => {
          const parentId = district.parentId
          if (parentId === cityId) {
            this.useDistrictList.push(district)
          }
        })
      },
      onShowVillage() {
        if (!this.districtCode) {
          this.$message({
            type: 'error',
            message: '必须先设置省市区才可以选择添加管理的小区!'
          })
          return
        }
        this.dialogPickVillageVisible = true
        if (this.selectedDistrictCode !== this.districtCode) {
          this.selectedDistrictCode = this.districtCode
          listByDistrictCode({
            enterpriseId: this.getEnterpriseId(),
            commanderId: this.commanderId,
            districtCode: this.districtCode
          }).then(response => {
            if (response.isError) return
            this.villageList = response.data
          })
        }
      },
      onPickVillage(row) {
        row.selectFlag = row.selectFlag === 1 ? 0 : 1
        if (!this.districtCode) {
          this.$message({
            type: 'error',
            message: '必须先设置省市区才可以选择添加管理的小区!'
          })
          return
        }
      },
      onSelectVillage() {
        this.villageNames = this.villageList.filter(v => v.selectFlag === 1).map(v => v.villageName).join('\n')
        this.villages = this.villageList.filter(v => v.selectFlag === 1).map(v => v)
        this.dialogPickVillageVisible = false
        this.entity.villages = this.villageList
      },
      onSetLocation() {
        if (window.loc && window.loc.latlng) {
          this.entity.lng = window.loc.latlng.lng
          this.entity.lat = window.loc.latlng.lat
          this.entity.takeAddress = window.loc.poiaddress
        }
        this.dialogMapVisible = false
      }
    }
  }
</script>
<style lang="less" scoped>
  .des-box{
    background: #f3f3f3;
    margin: 15px;
    padding: 25px;
    .balance-list{
      &:last-child{
        margin-top: -10px;
        margin-bottom: -10px;
      }
    }
    .time-input{
      width: 100%;
    }
    .bottom-btn{
      padding-left: 130px;
      padding-top: 15px;
    }
  }
  .mission-type {
    padding: 35px 38px;
    min-width: 150px;
    border: 1px solid #dcdcdc;
    border-radius: 8px;
    margin: 25px 40px;
    cursor: pointer;
    text-align: center;
    box-shadow: 0 0 5px rgba(0,0,0,0.1);
  }
  .flex-cag-box{
    padding: 0px 0px 20px 70px;
    .mission-type:nth-child(4n){
      margin-right: 0px;
    }
  }
  .next-step-btn{
    padding: 13px 35px;
    font-size: 18px;
  }

  .sel-mission-type {
    background-color: #409eff;
    color: #fff;
  }

  .budget-el-select {
    padding-top: 10px;
    padding-left: 50px;
  }

  .user-avatar{
    width: 46px;
    height: 46px;
    display: block;
    border-radius: 50px;
  }
</style>
